package com.godenwater.recv.server.sl651;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.gov.mwr.sl651.Symbol;
import cn.gov.mwr.sl651.IMessage;
import cn.gov.mwr.sl651.IMessageBody;
import cn.gov.mwr.sl651.IMessageHeader;
import cn.gov.mwr.sl651.utils.ByteUtil;

/**
 * 数据编码器
 * 
 * @ClassName: HexDataEncoder
 * @Description: TODO
 * @author lipujun
 * @date Feb 22, 2013
 * 
 */
public class ServerDataEncoder extends ProtocolEncoderAdapter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		
//session.getId()
		if (message instanceof IMessage) {
			logger.info("[编码报文] 下行编码报文...");
			// 获取消息体
			IMessage msg = (IMessage) message;
			IMessageHeader header = msg.getHeader();
			IMessageBody body = msg.getBody();

			// 构造缓冲区大小
			int capacity = header.getLength() + body.getLength() + 1;// 1表示结束标识位数

			byte[] SOH = header.getStartBit();
			if (SOH[0] == Symbol.SOH_ASC) { // ASCII码标识
				capacity = capacity + 4; // CRC占4个字节
			} else {// HEX码 7E7EH
				capacity = capacity + 2; // CRC占2个字节
			}

			// 开始写入数据
			IoBuffer buffer = IoBuffer.allocate(capacity, false); // 构造一个缓冲区
			buffer.setAutoExpand(true);
			buffer.put(header.getStartBit());
			buffer.put(header.getStationAddr());// 作为下行，遥测站地址在前，中心站地址在后
			buffer.put(header.getCenterAddr());
			buffer.put(header.getPassword());
			buffer.put(header.getFuncCode());
			buffer.put(header.getBodySize());
			buffer.put(header.getBodyStartBit());
			if (header.getBodyStartBit()[0] == Symbol.SYN) {
				buffer.put(header.getBodyCount());
			}
			buffer.put(body.getContent()); // 构造内容
			buffer.put(msg.getEOF()); // 构造结束符
			buffer.put(msg.getCRC()); // 构造CRC校验码

			buffer.flip();
			out.write(buffer);
		} else if (message instanceof byte[]) {
			
			byte[] msg = (byte[]) message;
			
			logger.info("[编码报文] 下发召测报文..." + ByteUtil.toHexString(msg));
			
			int capacity = msg.length;
			IoBuffer buffer = IoBuffer.allocate(capacity, false); // 构造一个缓冲区
			buffer.setAutoExpand(true);
			buffer.put(msg);
			buffer.flip();
			out.write(buffer);
		} else {
			logger.info("[编码报文] 报文类型不正确，不做下发处理！" + message.toString());
		}
	}

}
